package com.iotproject.forumservice.controller.admin;

import com.iotproject.commonutils.R;
import com.iotproject.forumservice.entity.ForumQuestion;
import com.iotproject.forumservice.entity.vo.admin.QuestionQuery;
import com.iotproject.forumservice.service.ForumQuestionService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("admin/forumservice/question/")
public class AdminForumQuestionController {

    @Autowired
    ForumQuestionService questionService;

    @PostMapping("pageQuestionCondition/{current}/{limit}")
    public R pageQuestionCondition(@PathVariable("current") long current,
                                  @PathVariable("limit") long limit,
                                  @RequestBody(required = false) QuestionQuery questionQuery) {
        Page<ForumQuestion> questionPage = new Page<>(current, limit);
        QueryWrapper<ForumQuestion> questionQueryWrapper = new QueryWrapper<>();

        String articleId = questionQuery.getId();
        String creatorId = questionQuery.getCreatorId();
        String title = questionQuery.getTitle();
        String tag = questionQuery.getTag();
        String begin = questionQuery.getBegin();
        String end = questionQuery.getEnd();
        if (!StringUtils.isEmpty(title)) {
            questionQueryWrapper.like("title", title);
        }
        if (!StringUtils.isEmpty(tag)) {
            questionQueryWrapper.like("tag", tag);
        }
        if (!StringUtils.isEmpty(articleId)) {
            questionQueryWrapper.eq("id", articleId);
        }
        if (!StringUtils.isEmpty(creatorId)) {
            questionQueryWrapper.eq("creator_id", creatorId);
        }
        if (!StringUtils.isEmpty(begin)) {
            questionQueryWrapper.ge("gmt_modified", begin);
        }
        if (!StringUtils.isEmpty(end)) {
            questionQueryWrapper.le("gmt_modified", end);
        }
        questionQueryWrapper.orderByDesc("gmt_modified");
        questionService.page(questionPage, questionQueryWrapper);
        long total = questionPage.getTotal();
        List<ForumQuestion> records = questionPage.getRecords();
        return R.ok().data("total", total).data("rows", records);
    }

    @DeleteMapping("deleteQuestionById/{id}")
    public R deleteQuestionById(@PathVariable("id") String id) {
        boolean removeById = questionService.removeById(id);
        if (removeById) {
            return R.ok();
        }
        return R.error();
    }

}
